/**
 * Created by hcadmin on 16/9/27.
 */
$(function(){
    var followers;
    var _token;
    var _userId;
    var _imToken;
    var _qyxBindId;
    var _group_id;
    var _name    = "";
    var _title   = "";
    var _event_name = "";
    var three_btn = "";
    var teamName = "";
    var dept = "";
    //获取页面间的url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    var index           = $.getUrlParam('index');               //待我审批-0;我已审批-1;我发起的-2;抄送我的-3
    var approval_id     = $.getUrlParam('id');                  //获取 审批id

    var token           = $.getUrlParam('token');               //获取分享过来的 token;
    var userId          = $.getUrlParam('userId');              //用户id
    var imToken         = $.getUrlParam('imToken');
    var qyxBindId       = $.getUrlParam('qyxBindId');
    var group_id        = $.getUrlParam('teamId');
    if(index==undefined){
        index = "5";
    }
    if(token==undefined){
        _token = localStorage.token;
        _userId = localStorage.user_id;
        _imToken = localStorage.imToken;
        _qyxBindId = localStorage.qyxBindId;
        _group_id = localStorage.group_id;

    }else{
        _token = token;
        _userId = userId;
        _imToken = imToken;
        _qyxBindId = qyxBindId;
        _group_id = group_id;

    }


    //选项框
    if (index == 3){
        $(".sub_again").hide();
        $(".only_cancel").css("border-bottom","none");
        $(".more_again").attr("style","height:15.4375vh");
    }


    var last_id = 0;
    //第三模块最后一条
    var current_html2;
    var current_html3;

    var html_process2;
    var html_process3;

    var current_approver;

    //获取个人所在团队
    //getTeamName();

    //弹出框
    $("#call_back").on('click',function(){
        $(".more_again").hide();
        $(".content_big").show();
        $(".title_big").html("确定撤销该审批申请?");
        $(".only_cancel").hide();
        $(".okCancel").show();
        $(".call_back").fadeIn(150);
    });
    $(".cancel").on('click',function(){
        $(".call_back").fadeOut(150);
    });
    $("#sure").on('click',function(){
        var data = {
            user_id:_userId,
            token:_token,
            imtoken:_imToken,
            qyxBindId:_qyxBindId,
            title:_name+"的"+_title+"已撤回"
        };
        $.ajax({
            beforeSend:function(){
                $(".content_big").hide();
                //$(".content_big").fadeOut(100,function(){
                    $(".call_back_success").html("正在撤销...").show();
                //});
            },
            //url:apiurl+"/approvals/"+approval_id+"?user_id="+_userId+"&token="+_token+"&imtoken="+_imToken+"&qyxBindId="+_qyxBindId+"&title="+_name+"的"+_title+"已撤回"+"",
            url:apiurl+"/approvals/"+approval_id+"/delete",
            type:"POST",
            data:data,
            success:function(d){
                if(typeof d == "object"){
                    var msg= d.msg;
                    if(msg=="202") {
                        $(".token_iframe").fadeIn(1000);
                    }
                }else{
                    var code = JSON.parse(d).code;
                    if(code==0){
                        $(".call_back_success").hide().html("撤销成功").show().fadeOut(500,function(){
                            window.location.reload();
                        });
                    }
                }
            }
        });
    });

    //点击“更多”
    if(index=="2"||index=="3"){
        moreOption();
    }else{
        $(".approval_nav_right").on('click',function(){
            $(".more_again").hide();
            $(".content_big").show();
            $(".title_big").html("分享");
            $(".okCancel").hide();
            $(".only_cancel").show();
            $(".call_back").fadeIn(150);
        });
        $(".title_big").on('click',function(){
            //var attId           ="";
            //var team            =localStorage.group_id;
            //var content         ="审批分享";
            //var title           =_event_name;
            //var applicationId   =approval_id;
            //var applicationType =5;
            //var attSize         ="";
            //var hyperlink       ="/approval/html/approvalDetail.html?id="+approval_id+"";
            //
            //shareContent(attId,team,content,title,applicationId,applicationType,attSize,hyperlink);
            share();
        })
    }
    function moreOption(){
        $(".approval_nav_right").on('click',function(){
            $(".content_big").hide();
            $(".more_again").show();
            $(".title_big").html("分享");
            $(".okCancel").hide();
            $(".only_cancel").show();
            $(".call_back").fadeIn(150);
            //点击分享
            $(".share").on('click',function(){
                share();
            });
            //点击重新提交
            $(".sub_again").on('click',function(){
                window.location.href="approvalModel.html?approval_id="+approval_id+"&edit=1";
            });
        });
    }
    function share(){
        var attId           ="";
        var team            =localStorage.group_id;
        var content         ="审批分享";
        var title           =_event_name;
        var applicationId   =approval_id;
        var applicationType =5;
        var attSize         ="";
        var hyperlink       ="/approval/html/approvalDetail.html?id="+approval_id+"";

        shareContent(attId,team,content,title,applicationId,applicationType,attSize,hyperlink);
    }
    $(".only_cancel").on('click',function(){
        $(".call_back").fadeOut();
    });



    //$(window).bind("pageshow", function(event) {
    //    //if (event.originalEvent.persisted) {
    //    //    window.location.reload()
    //    //}
    //    alert("hhhh");
    //});




    function initData(){
        //调用接口的URL
        var url =apiurl+"/approvals/"+approval_id+"";
        $.ajax({
            beforeSend:function(){
                $(".loading").show();
                $(".show_hide").hide();
                $(".bottom_icon").hide();
            },
            url:url,
            async:true,
            data:{
                user_id:_userId,
                token:_token
            },
            success:function(d){
                if(typeof d == "object"){
                    var msg= d.msg;
                    if(msg=="202") {
                        $(".token_iframe").fadeIn(1000);
                    }
                }
                else
                {
                    $(".loading").hide();
                    $(".show_hide").show();
                    $(".bottom_icon").show();
                    var start_time              = "";
                    var stop_time               = "";
                    var value                   = "";
                    var files;
                    var extra                   = "";
                    var html                    = "";

                    var data                    = JSON.parse(d).data;                               //获取数据
                    var userInfo                = data.userCallbackString;                          //用户列表

                    var approval_status         = "";                                               //审批状态(待审批,已完成)
                    var del_flag                = data.del_flag;                                    //是否撤销
                    var status                  = data.approval_status;                             //数据中的审批状态(0,1,2)
                    var user_id                 = data.user_id;                                     //审批提交这用户id
                    _group_id                   = data.group_id;
                    var user_name;
                    var user_icon;
                    var user_qyxBindId;
                    var dpt;
                    for(var b=0;b<userInfo.length;b++){
                        if(userInfo[b].id==user_id){
                            user_name = userInfo[b].name;
                            _name     = user_name;
                            user_icon = userInfo[b].avatar;
                            user_qyxBindId  = userInfo[b].qyxBindId;
                            dpt       = userInfo[b].dep.deptName;

                        }
                    }


                    var avatar_img;
                    var avatar_img_s;
                    //if(user_icon==""){
                        var color = avatar_getColor(user_qyxBindId);
                        avatar_img = "<div class='detail_left_pic' style='background-color: "+color+"'>"+avatar_name(user_name)+"</div>";
                        avatar_img_s = "<div class='detail_left_pic2' style='background-color: "+color+"'>"+avatar_name(user_name)+"</div>";
                    //}else{
                    if (user_icon.length > 0){
                        //var img = new Image(), url = img.src = get_url;
                        //var $img = $(img);
                        //img.onerror = function() {
                        //
                        //
                        //    //URL.revokeObjectURL(url)
                        //    //$('#banner-pic').empty().append($img);
                        //
                        //    get_url = "";
                        //};
                        //img.onload = function() {
                        //
                        //}

                        var src = avatar_getUrl(_userId,_token,user_icon);
                        avatar_img += "<img class='detail_left_pic' src='"+src+"' hidden>";
                        avatar_img_s += "<img class='detail_left_pic2' src='"+src+"' hidden>";
                    }
                    var approval_id             = data.approval_id;                                 //审批id
                    var create_timestamp        = data.create_timestamp;                            //审批创建的时间戳
                    var update_timestamp        = data.update_timestamp;
                    var approval_model_name     = data.approvalTemp.approval_title;                 //使用模板的名称
                    var event_name              = user_name+"的"+approval_model_name;               //拼接成  完整 的 出差
                    _event_name                 = event_name;
                    var components              = data.approvalTemp.components;                     //获取模板组件
                    var componentValue          = data.componentValue;                              //获取填写的值
                    followers                   = data.followers;                                   //抄送人
                    var details                 = data.details;                                     //审批人意见详情
                    current_approver            = data.current_approver;                            //当前审批人
                    var user_name2;
                    var user_icon2;
                    var user_qyxBindId2;

                    for(var g=0;g<userInfo.length;g++){
                        if(userInfo[g].id == current_approver){
                            user_name2 = userInfo[g].name;
                            user_icon2 = userInfo[g].avatar;
                            user_qyxBindId2 = userInfo[g].qyxBindId;
                        }
                    }
                    var current_img;
                    //if(user_icon2==""){
                        var current_color = avatar_getColor(user_qyxBindId2);
                        current_img = "<div class='detail_left_pic2' style='background-color: "+current_color+"'>"+avatar_name(user_name2)+"</div>";

                    //}else{
                    if (user_icon2.length >0) {
                        var current_src = avatar_getUrl(_userId,_token,user_icon2);
                        current_img += "<img class='detail_left_pic2' src='"+current_src+"' hidden>";
                    }
                    _title                      = approval_model_name;

                    if(del_flag=="1"){
                        approval_status = "已撤回";
                        $(".watermark").hide();
                        $(".watermark2").hide();
                    }else{
                        if(status=="0"){
                            if(index=='2'||index=='5'){
                                approval_status = "等待"+user_name2+"审批";
                            }else{
                                approval_status = "等待我审批";
                            }
                            $(".watermark").hide();
                            $(".watermark2").hide();
                        }else if(status=="1"){
                            approval_status = "审批完成（同意）";
                            $(".watermark").show();
                            $(".watermark2").hide();
                        }else{
                            approval_status = "审批完成（拒绝）";
                            $(".watermark").hide();
                            $(".watermark2").show();
                        }
                    }
                    //标题
                    $(".title").html(event_name);
                    //第一个div
                    $(".approval_name").html(event_name);
                    $(".approval_style").html(approval_status);
                    $(".detail_left_small").append(avatar_img);

                    //第二快模板展示
                    $(".model_content").append("<div class='detail_small'>审批编号: <span class='real_content'>"+approval_id+"</span></div>")
                        .append("<div class='detail_small'>所在部门: <span class='real_content' id='depart'></span></div>");


                    approvalDepartment();

                    //模板详情的展示
                    for(var i=0;i<components.length;i++){
                        var approval_temp_component_id  = components[i].approval_temp_component_id;//获取模板组件的id
                        var component_title             = components[i].component_title;           //获取组件的title
                        //时间组件的  开始时间  结束时间   文字
                        var component_start_title;
                        var component_end_title;
                        var component_type              = components[i].component_type;             //获取模板类型
                        var component_formatter         = components[i].component_formatter;
                        var component_unit              = components[i].component_unit;

                        for(var a=0;a<componentValue.length;a++){
                            value = componentValue[a].default_value;
                            extra = componentValue[a].extra_value;
                            //判断模板对应的值
                            if(componentValue[a].approval_temp_component_id == approval_temp_component_id){
                                /*0：单行输入框 1：多行输入框 2：单选 3：多选 4：日期 5：时间区间 6：图片 7：明细 8：说明文字 9：金额 10：附件 13：数字输入框*/
                                if(component_type=="4"){
                                    if(value!=""){
                                        var timestamp = Math.round(value);
                                        value = timestampToString(timestamp,component_formatter);
                                    }else{
                                        value = "";
                                    }
                                    initComponents(component_type,component_title,value,"model_content");
                                }else if(component_type=="5"){
                                    component_start_title = components[i].component_start_title;
                                    component_end_title = components[i].component_end_title;
                                    if(value!="") {
                                        var timestamp = Math.round(value);
                                        start_time = timestampToString(timestamp, component_formatter);
                                    }else{
                                        start_time="";
                                    }
                                    if(extra!=""){
                                        var timestamp = Math.round(extra);
                                        stop_time = timestampToString(timestamp,component_formatter);
                                    }else{
                                        stop_time = "";
                                    }
                                    var component_autoincrease = components[i].component_autoincrease;
                                    initComponent5(component_type,component_start_title,component_end_title,start_time,stop_time,"model_content",component_autoincrease,component_formatter);
                                }else if(component_type=="6"){
                                    value = componentValue[a].default_value;
                                    var array = value.split(",");
                                    html = "<div class='detail_small'>"+component_title+":</div>";
                                    if(value!=""){
                                        for(var arr=0;arr<array.length;arr++){
                                            html += "<img class='detail_approval_date_pic model_img' src='"+array[arr]+"'>";
                                        }
                                    }
                                    $(".model_content").append(html);
                                }
                                else if(component_type=="7"){

                                    var child = componentValue[a].child;

                                    //循环 获取child

                                    //temp_id:{title: unit: total:}
                                    var complexDic = {};


                                    for(var c = 0;c < child.length; c++){
                                        var number = c + 1;


                                        $(".model_content").append("<div class='detail_small'><div class='one_pic'>"+ number +"</div>&nbsp;&nbsp;明细详情</div>");
                                        //循环获取 值
                                        for(var e=0;e<child[c].length;e++){

                                            value = child[c][e].default_value;
                                            extra = child[c][e].extra_value;
                                            var child_id = child[c][e].approval_temp_component_id;


                                            //循环获取title
                                            for(var f = 0;f < components[i].child.length; f++){




                                                component_title = components[i].child[f].component_title;
                                                component_type  = components[i].child[f].component_type;
                                                component_unit  = components[i].child[f].component_unit;
                                                var parent_id = components[i].child[f].parent_component_id;


                                                //var component_unit = compoentChild.component_unit;
                                                var formatter   = components[i].child[f].component_formatter;

                                                if(child_id==components[i].child[f].approval_temp_component_id){
                                                    if(component_type=="4"){
                                                        if(value!=""){
                                                            var timestamp = Math.round(value);
                                                            value = timestampToString(timestamp,formatter);
                                                        }else{
                                                            value = "";
                                                        }
                                                        initComponents(component_type,component_title,value,"model_content");
                                                    }else if(component_type=="5"){
                                                        component_start_title = components[i].child[f].component_start_title;
                                                        component_end_title = components[i].child[f].component_end_title;
                                                        if(value!=""){
                                                            var timestamp = Math.round(value);
                                                            start_time = timestampToString(timestamp,formatter);
                                                        }else{
                                                            start_time = "";
                                                        }
                                                        if(extra!=""){
                                                            var timestamp = Math.round(extra);
                                                            stop_time = timestampToString(timestamp,formatter);
                                                        }else{
                                                            stop_time = "";
                                                        }
                                                        var component_autoincrease = components[i].child[f].component_autoincrease;
                                                        initComponent5(component_type,component_start_title,component_end_title,start_time,stop_time,"model_content",component_autoincrease,formatter);
                                                    }else if(component_type=="6"){
                                                        var array1 = value.split(",");
                                                        html = "<div class='detail_small'>"+component_title+":</div>";
                                                        if(value!=""){
                                                            for(var arr1=0;arr1<array1.length;arr1++){
                                                                html += "<img class='detail_approval_date_pic model_img' src='"+array1[arr1]+"'>";
                                                            }
                                                        }
                                                        $(".model_content").append(html);
                                                    }else if(component_type=="10"){
                                                        files = child[c][e].files;
                                                        html = "<div class='detail_small'>附件:</div>";
                                                        if(files.length>0){
                                                            for(var arr21=0;arr21<files.length;arr21++){
                                                                var file_name1 = files[arr21].file_name;
                                                                var file_size1 = files[arr21].file_size;
                                                                html += "<div class='file_big'><div class='file_content'><div class='col-xs-2 content_height'><img src='../../approval/approvalImg/Giab/file_icon.png' class='file_img'></div><div class='col-xs-10 content_height'><div class='file_name'>"+file_name1+"</div><div class='file_size'>"+file_size1+"</div></div></div></div>";
                                                            }
                                                        }
                                                        $(".model_content").append(html);
                                                    }else{
                                                        initComponents(component_type,component_title,value,"model_content",component_unit,parent_id);
                                                    }
                                                }
                                            }

                                            //统计
                                            var valueChild = child[c][e];

                                            if (valueChild.component_type == "13" || valueChild.component_type == "9"){
                                                //如果是13 或者 9 也就是数字或金额 则需要统计
                                                //记录

                                                var temp = components[i].child[e];

                                                //存储的key
                                                var key = valueChild.approval_temp_component_id;
                                                //var new_value = compoentChild.


                                                if (valueChild.child_tag == "0"){
                                                    var value = valueChild.default_value;
                                                    if (value.length == 0){
                                                        value = 0;
                                                    }
                                                    var object = {title:temp.component_title,unit:temp.component_unit,total:value,type:valueChild.component_type};
                                                    complexDic[key] = object;
                                                }else {
                                                    var value = valueChild.default_value;
                                                    if (value.length == 0){
                                                        value = 0;
                                                    }
                                                    var object = complexDic[key];
                                                    var last_value = object.total;
                                                    var current_value = parseFloat(last_value) + parseFloat(value);
                                                    object.total = current_value;
                                                    complexDic[key] = object;
                                                }



                                            }
                                        }

                                    }

                                    //遍历统计
                                    var count = 0;

                                    for (var key in complexDic){
                                        if (count == 0){
                                            var space = "<div class='space_small'>&nbsp;</div>";
                                            $(".model_content").append(space);

                                        }

                                        var object = complexDic[key];

                                        if (object.total == 0){
                                            object.total = "";
                                        }


                                        initComponents(object.type,"总"+object.title,object.total,"model_content",object.unit);

                                        count++;
                                    }

                                    var total_html = "<div class='space_large'>&nbsp;</div>";
                                    $(".model_content").append(total_html);


                                }else if(component_type=="10"){
                                    files = componentValue[a].files;

                                    html = "<div class='detail_small'>附件:</div>";
                                    if(files!=undefined){
                                        if(files.length>0){
                                            for(var arr2=0;arr2<files.length;arr2++){
                                                var file_name = files[arr2].file_name;
                                                var file_size = files[arr2].file_size;
                                                var filr_url  = files[arr2].file_url;

                                                var isImg = checkImageType(file_name);
                                                var file_icon = "../../approval/approvalImg/Giab/file_icon.png";
                                                if (isImg == false){
                                                    file_icon = "../../approval/approvalImg/word.png";
                                                }

                                                html += "<div class='file_big'><div class='file_content file_download' file_data='"+filr_url+"' file_name='"+file_name+"'><div class='col-xs-2 content_height'><img src='"+ file_icon +"' class='file_img'></div><div class='col-xs-10 content_height'><p class='file_name'>"+file_name+"</p><p class='file_size'>"+file_size+"</p></div></div></div>";
                                            }
                                        }
                                    }
                                    $(".model_content").append(html);
                                }else{
                                    initComponents(component_type,component_title,value,"model_content",component_unit);
                                }

                            }
                        }
                    }


                    //第三块的数据展示

                    //审批提交信息
                    if (current_approver){
                        var current_body =
                            "<div class='detail_tableview_cell_mid2'>" +
                                "<img src='../approvalImg/waitApprovalTime.png' class='green_right'>" +
                                "<div class='detail_left_small2  me_icon col-xs-2' style='height: 100%'>"+current_img+"</div>" +
                                "<div class='detail_right_small2 col-xs-10'>" +
                                    "<p  class='approval_name2'>"+user_name2+"</p>" +
                                    "<p  class='approval_style2' style='color: #EBA84E'>审批中</p>" +
                                "</div>" +
                                "<div class='col-xs-6'></div>" +
                            "</div>";


                        current_html2 =
                            "<div class='detail_tableview_cell_div'> "
                            + current_body +
                            "</div>";
                        current_html3 =
                            "<div class='detail_tableview_cell_div2'>" +
                            "<div class='finishDiv'></div>"
                            + current_body +
                            "</div>";
                    }


                    //创建时间
                    var createTime = timestampToString(create_timestamp,"yyyy.MM.dd HH:mm");

                    //审批发起人
                    var approvalSubmitInfoDiv=
                        "<div class='detail_tableview_cell_div'>" +
                            "<div class='do_bigest'>"+
                            "<div class='detail_tableview_cell_mid_do'>" +
                                "<img src='../approvalImg/green_right.png' class='green_right'>" +
                                "<div class='detail_left_small2 approval_man me_icon col-xs-2' style='height: 100%'>"+avatar_img_s+"</div>" +
                                "<div class='detail_right_small2 col-xs-10'>" +
                                    "<div class='approval_name_comment'>" +
                                        "<div class='col-xs-6 approval_name_do' style='padding-left: 0px;'>"+user_name+"</div>" +
                                        "<div class='col-xs-6 detail_time' style='text-align: center;margin-top: 1.08333vh'>" + createTime + "</div>" +
                                    "</div>" +
                                    "<div class='approval_style2'>发起申请</div>" +
                                "</div>" +
                            "</div>" +
                            "</div>" +
                        "</div>";
                    $(".comment_div").append(approvalSubmitInfoDiv);


                    //var html1 =

                    ////var html2 = "<div class='approval_name2'>"+approval_name+"</div>";
                    //var html_process =
                    //    "<div class='do_bigest'>"+
                    //        "<div class='detail_tableview_cell_mid_do'>" +
                    //            "<img src='" + img_url + "' class='green_right'>"+
                    //            "<div class='detail_left_small2 col-xs-2' style='height: 100%'>" + img_url1 + "</div>" +
                    //            "<div class='detail_right_small2 col-xs-10'>" +
                    //                html1 + add_html + "</div>" +
                    //        "</div>" +
                    //        "<div class='do_img_content'>" + html_img_do + "</div>" +
                    //            html_file_do +
                    //    "</div>";
                    //add_html = "<div  class='approval_style2'>"+result+"<span class='agree'>"+result_grey+"</span></div>";

                    //插入当前审批状态 没有审批操作的情况下
                    //var relation_count = 0;
                    //for (var i = 0; i < details.length; i ++){
                    //    var object = details[i];
                    //    if (object.approval_relation_id){
                    //        relation_count ++;
                    //    }
                    //}
                    //if (relation_count == 0 && status == "0"){
                    //    if (details.length > 0){
                    //        $(".comment_div").append(current_html2);
                    //    }else {
                    //        if (del_flag == "1"){
                    //            $(".comment_div").append(current_html2);
                    //        }else {
                    //            $(".comment_div").append(current_html3);
                    //        }
                    //
                    //    }
                    //
                    //}




                    var cancelTime = timestampToString(update_timestamp,"yyyy.MM.dd HH:mm");




                    var approvalCancelBody =
                        "<div class='detail_tableview_cell_mid2'>" +
                            "<img src='../approvalImg/green_right.png' class='green_right'>" +
                            "<div class='detail_left_small2 approval_man_back me_icon col-xs-2' style='height: 100%'>"+avatar_img_s+"</div>" +
                            "<div class='detail_right_small2 col-xs-10'>" +
                                "<div class='approval_name_comment'>" +
                                    "<div class='col-xs-6 approval_name_do' style='padding-left: 0px;'>"+user_name+"</div>" +
                                    "<div class='col-xs-6 detail_time' style='text-align: center;margin-top: 1.08333vh'>" + cancelTime + "</div>" +
                                "</div>" +
                                "<div class='approval_style2' style='margin-top: -2vh'>已撤销</div>" +
                            "</div>" +

                            //"<div class='detail_right_small2 col-xs-4'>" +
                            //    "<p class='approval_name2'>"+ user_name +"</p>" +
                            //    "<p class='approval_style2'>已撤销</p>" +
                            //"</div>" +
                            //"<div class='col-xs-6 detail_time del_flag_time'>"+ cancelTime +"</div>" +
                        "</div>";

                    var cancel_status = "-1";//-1 没有撤销;0 撤销


                    //if (del_flag == "1") {
                    //    cancel_status = "0";
                    //}

                    if (details.length == 0){
                        //没有审批详情 直接在这里处理 审批状态
                        if (del_flag == "1"){
                            //审批撤销
                            var approvalCancelDiv =
                                "<div class='detail_tableview_cell_div2 del_flag_big'>" +
                                "<div class='finishDiv'></div>" + approvalCancelBody +
                                "</div>";
                            $(".comment_div").append(approvalCancelDiv);
                            cancel_status = 0;
                        }else {
                            //暂无
                        }
                    }else {
                        if (del_flag == "1"){
                            var first = details[0];
                            var last = details[details.length - 1];

                            var first_timestamp = first.timestamp;
                            var last_timestamp = last.timestamp;

                            if (first_timestamp > update_timestamp){
                                //在所有操作之前
                                var approvalCancelDiv =
                                    "<div class='detail_tableview_cell_div del_flag_big'>"
                                    + approvalCancelBody +
                                    "</div>";
                                $(".comment_div").append(approvalCancelDiv);
                                cancel_status = "0";
                            }else if (update_timestamp > last_timestamp){
                                //在所有操作之后
                                cancel_status = "2";
                            }else {
                                //在某次操作中间
                                cancel_status = "1";
                            }
                        }
                    }




                    //审批流程
                    for (var i = 0; i < details.length; i ++){
                        var object = details[i];

                        var isLast = false;
                        if (i == details.length - 1){
                            isLast = true;
                        }


                        if (object.approval_relation_id){

                            var last_relation_index = 0;
                            //是不是最后一条审批操作
                            for (var j = 0; j < details.length; j ++){
                                var compare_object = details[j];
                                if (compare_object.approval_relation_id){
                                    last_relation_index = j;
                                }
                            }

                            var is_last_relation = false;
                            if (last_relation_index == i){
                                is_last_relation = true
                            }

                            displayApproveDetail(object,userInfo,isLast,status,is_last_relation,cancel_status);
                        }else {
                            displayComment(object,userInfo,isLast,status,cancel_status);
                        }

                        if (cancel_status == "1" && i < details.length - 1){
                            var nextObject = details[i+1];

                            var current_time = object.timestamp;
                            var next_time = nextObject.timestamp;

                            if (update_timestamp >= current_time && update_timestamp <= next_time){
                                //插入撤销
                                var approvalCancelDiv =
                                    "<div class='detail_tableview_cell_div del_flag_big'>"
                                    + approvalCancelBody +
                                    "</div>";
                                $(".comment_div").append(approvalCancelDiv);
                            }

                        }
                    }
                    if (status == "0" && cancel_status == "-1"){
                        //if (cancel_status == "2"){
                        //    $(".comment_div").append(current_html2);
                        //}else {
                        $(".comment_div").append(current_html3);
                        //}

                    }

                    if (cancel_status == "2"){
                        //撤销在所有操作之后
                        var approvalCancelDiv =
                            "<div class='detail_tableview_cell_div2 del_flag_big'>" +
                            "<div class='finishDiv'></div>" + approvalCancelBody +
                            "</div>";
                        $(".comment_div").append(approvalCancelDiv);
                    }

                    //删除时间
                    if(del_flag=="1"){
                        //var time2 = new Date(update_timestamp);
                        //initDate(time2);
                        //$(".del_flag_time").text(whole_time);
                        $(".del_flag_big").show();
                    }else{
                        $(".del_flag_big").hide();
                    }





                    //----抄送人
                    if(followers.length>0){
                        var followers_arr = followers.split(",");
                        for(var a1=0;a1<followers_arr.length;a1++){
                            var name;
                            var avatar;
                            var qxy;
                            for(var x=0;x<userInfo.length;x++){
                                if(followers_arr[a1]==userInfo[x].id){
                                    name   = userInfo[x].name;
                                    avatar = userInfo[x].avatar;
                                    qxy    = userInfo[x].qyxBindId;
                                }
                            }
                            var avatar_img2;
                            //if(avatar=="") {
                                var color2 = avatar_getColor(qxy);
                                avatar_img2 = "<div class='cope_me_cover' style='background-color: "+color2+"'>"+avatar_name(name)+"</div>"
                            //}else{
                            if (avatar.length > 0) {
                                var src2 = avatar_getUrl(_userId,_token,avatar);
                                avatar_img2 += "<img src='"+src2+"' class='cope_me_cover' hidden>";
                            }
                            $(".copy_me_down").append("<div class='copy_me_person'>"+avatar_img2+"<div class='cope_me_name'>"+name+"</div></div>");
                        }
                    }else{
                        $(".copy_me").css('display','none');
                    }

                    //底部评论框  同意 拒绝 0-待我审批 1-我已审批 2-我发起的
                    $("#bottom_icon").show();
                    if(index==0){
                        $("#0").show();$("#1").hide();$("#2").hide();$("#3").hide();$("#4").hide();$("#5").hide();
                        $("#approval_back").on('click',function(){
                            //window.history.back(-1);
                            //window.history.go(-1);
                            //window.location.go(-1);



                            window.location.href="waitApproval.html?index="+ $.getUrlParam('before_index') +"";
                        })
                    }
                    if(index==1) {
                        $("#0").hide();$("#1").show();$("#2").hide();$("#3").hide();$("#4").hide();$("#5").hide();
                        $("#approval_back").on('click',function(){
                            //window.history.back(-1);

                            window.location.href="waitApproval.html?index="+ $.getUrlParam('before_index') +"";
                        })
                    }
                    if(index==2){
                        $("#0").hide();$("#1").hide();$("#4").hide();$("#5").hide();
                        if(del_flag=="1"){
                            //已经撤销的 (只显示评论)
                            $("#2").hide();$("#3").show();
                        }else{
                            //没有撤销的
                            $("#2").show();$("#3").hide();
                        }
                        $("#approval_back").on('click',function(){
                            window.location.href="meStart.html";
                        })
                    }
                    if(index==3) {
                        $("#0").hide();$("#1").hide();$("#2").hide();$("#3").show();$("#4").hide();$("#5").hide();
                        $("#approval_back").on('click',function(){
                            window.location.href="copyMe.html";
                        })
                    }
                    if(index==4) {
                        $("#0").hide();$("#1").hide();$("#2").hide();$("#3").hide();$("#4").show();$("#5").hide();
                        $("#approval_back").on('click',function(){
                            window.location.href="meStart.html";
                        })
                    }
                    //----分享进来的页面
                    if(index==5){
                        if(del_flag=="1"){
                            $("#0").hide();$("#1").hide();$("#4").hide();$("#2").hide();$("#3").hide();$("#5").show();
                        }else{
                            if(status=="0"){
                                //如果是自己点进去
                                //如果是审批人点进去
                                //其他
                                if(_userId==current_approver&&_userId==user_id){
                                    $("#0").hide();$("#1").hide();$("#2").show();$("#3").hide();$("#4").hide();$("#5").hide();
                                    //右上角的更多
                                    moreOption();
                                }else{
                                    if(_userId==current_approver){
                                        $("#0").show();$("#1").hide();$("#2").hide();$("#3").hide();$("#4").hide();$("#5").hide();
                                    }else if(_userId==user_id){
                                        $("#0").hide();$("#1").hide();$("#2").show();$("#3").hide();$("#4").hide();$("#5").hide();
                                        //右上角的更多
                                        moreOption();
                                    }else{
                                        $("#0").hide();$("#1").hide();$("#2").hide();$("#3").hide();$("#4").hide();$("#5").show();
                                    }
                                }
                            }else{
                                $("#0").hide();$("#1").hide();$("#4").hide();$("#2").hide();$("#3").hide();$("#5").show();
                            }
                        }


                        var quitShare;
                        quitShare                    = document.createElement('iframe');
                        quitShare.style.display      = 'none';
                        document.documentElement.appendChild(quitShare);
                        $("#approval_back").on('click',function(){
                            quitShare.src = "/quitShare_goBack";
                        })
                    }
                    showAvatar(".detail_left_pic");
                    showAvatar(".detail_left_pic2");
                    showAvatar(".cope_me_cover");
                    showAvatar(".person_img");
                }
                //initCommit(1);
            }
        });

        function dateStringToTimestamp(dateString){
            if (dateString.split(" ").length == 0){
                dateString = dateString + " 00:00:00";
            }
            var time = new Date(Date.parse(new Date(dateString)));
            return time.getTime();
        }

        function calDuringTime(start_time,stop_time,component_formatter){
            var start_timestamp = dateStringToTimestamp(start_time);
            var end_timestamp = dateStringToTimestamp(stop_time);

            var during = (end_timestamp - start_timestamp)/1000;




            var time = 0;
            if (during != NaN && during > 0){

                if (component_formatter.split(" ").length == 1){
                    //天
                    time = parseInt(during/86400);
                    time = time + 1;
                }else {
                    //小时
                    time = parseInt(during/3600);

                    var remain = during%3600;
                    //超过半天计0.5
                    if (remain >= 1800){
                        time = time + 0.5;
                    }
                }
                //$($(this).parent().parent().parent().find(".date_text")).text(time);
            }else if (during == 0){
                if (component_formatter.split(" ").length == 1){
                    //天
                    time = 1;
                    //$($(this).parent().parent().parent().find(".date_text")).text(time);
                }

            }
            return time;


            //if (during != NaN && during > 0){
            //
            //    //if (component_formatter.split(" ").length == 0){
            //    //    //天
            //    //    time_unit = "(天)";
            //    //}else {
            //    //    //小时
            //    //    time_unit = "(小时)";
            //    //}
            //
            //    var time = 0;
            //    if (component_formatter.split(" ").length == 0){
            //        //天
            //        time = parseInt(during/86400);
            //    }else {
            //        //小时
            //        time = parseFloat(during/3600.0);
            //        time = time.toFixed(2);
            //    }
            //
            //    //计算天数
            //    //var timediff = $endtime-$starttime;
            //    //var days = parseInt(during/86400);
            //    ////计算小时数
            //    //var remain = during%86400;
            //    //var hours = parseInt(remain/3600);
            //    ////计算分钟数
            //    //remain = remain%3600;
            //    //var mins = parseInt(remain/60);
            //    ////计算秒数
            //    //var secs = remain%60;
            //    //
            //    //console.log(days + "  " + hours + "  " + mins + "  " + secs);
            //
            //    return time;
            //}
            //return "";

        }

        //initCommit();
        //模板添加
        var html;
        function initComponent5(type,start_title,stop_title,start_time,stop_time,id,component_autoincrease,component_formatter){
            switch(type){
                case 5:
                    var duringText = calDuringTime(start_time,stop_time,component_formatter);





                    var during_html = "";
                    if (component_autoincrease == 1){

                        var time_unit = "";
                        if (component_formatter.split(" ").length == 1){
                            //天
                            time_unit = "(天)";
                        }else {
                            //小时
                            time_unit = "(小时)";
                        }

                        during_html = "<div class='detail_small'>时长"+ time_unit +": <span class='real_content'>"+duringText+"</span></div>";
                    }

                    html =
                        "<div class='detail_small'>"+start_title+": <span class='real_content'>"+start_time+"</span></div>" +
                        "<div class='detail_small'>"+stop_title+": <span class='real_content'>"+stop_time+"</span></div>" +
                        during_html;
                    break;
                default:
                    break;
            }
            $("."+id+"").append(html);
        }
        function initComponents(type,title,value,id,unit,parent_id){
            if (!unit){
                unit = "";
            }

            var html1 = "<div class='detail_small'>"+title+": <span class='real_content'>"+value+unit+"</span></div>";
            switch(type){
                case 0:
                    html = html1;
                    break;
                case 1:
                    var arr = value.split('\n');
                    var html_single = "";
                    for(key in arr){
                        html_single += "<div class='real_content'>"+arr[key]+"</div>";
                    }
                    html = "<div class='detail_small'><div class='mutil_title'>"+title+": </div><div class='mutil_content' style='width: auto'>"+html_single+"</div></div>";
                    break;
                case 2:
                    html = html1;
                    break;
                case 3:
                    var arr1 = value.split(',');
                    var html_single1 = "";
                    for(key1 in arr1){
                        html_single1 += "<div class='real_content'>"+arr1[key1]+"</div>";
                    }
                    html = "<div class='detail_small'><div class='mutil_title'>"+title+": </div><div class='mutil_content'>"+html_single1+"</div></div>";
                    break;
                    //html = html1;
                    //break;
                case 4:
                    html = html1;
                    break;
                case 8:
                    html = html1;
                    break;
                case 9:

                    var capital_html = "";
                    if (!parent_id || parent_id == "0"){
                        capital_html = "<div class='detail_small'>金额大写: <span class='real_content'>"+convertCurrency(value)+"</span></div>";
                    }

                    html = html1 + capital_html;
                    break;
                case 13:

                    html = html1;

                    break;
                default:
                    break;
            }

            $("."+id+"").append(html);
        }
    }

    //var stop=true;//触发开关，防止多次调用事件
    //$(window).scroll(function() {
    //    //当内容滚动到底部时加载新的内容 100当距离最底部100个像素时开始加载.
    //    if ($(this).scrollTop() + $(document).height() +1000>= $(document).height()) {
    //        if (stop == true) {
    //            stop = false;
    //            //$(".comment_div_model").remove();
    //            initCommit(0);
    //        }
    //    }
    //});


    function displayComment(comment,userInfo,isLast,status,cancel_status){

        var user_id              = comment.user_id;
        var user_icon;
        var user_name;
        var user_qyxBindId;
        for(var g = 0; g < userInfo.length; g++){

            if(userInfo[g].id==user_id){
                user_icon = userInfo[g].avatar;
                user_name = userInfo[g].name;
                user_qyxBindId  = userInfo[g].qyxBindId
            }
        }
        var avatar_img;
        //if(user_icon=="") {
            var color = avatar_getColor(user_qyxBindId);
            avatar_img = "<div class='person_img' style='background-color: "+color+"'>"+avatar_name(user_name)+"</div>"
        //}else{
        if (user_icon.length > 0){
            var src = avatar_getUrl(_userId,_token,user_icon);
            avatar_img += "<img src='"+src+"' class='person_img' hidden>";
        }

        var comment_body         = comment.comment_body;
        var comment_img          = comment.comment_img;
        var comment_file         = comment.comment_file;
        var timestamp            = comment.timestamp;
        var id                   = comment.approval_comment_id;
        var files                = comment.files;
        var img_arr              = comment_img.split(",");
        var file_arr             = comment_file.split(",");


        var displyTime = timestampToString(Math.round(timestamp),"yyyy.MM.dd HH:mm");

        var html_start =
            "<div class='comment_div_model' id='"+id+"'>" +
                "<img src='../approvalImg/threeDots.png' class='green_right'>" +
                "<div class='person_cover col-xs-2' style='height: auto'>" + avatar_img + "</div>" +
                "<div class='detail_right_small2 col-xs-10'>" +
                    "<div class='approval_name_comment'>" +
                        "<div class='col-xs-6 approval_name_do' style='padding-left: 0px;'>"+user_name+"</div>" +
                        "<div class='col-xs-6 detail_time' style='text-align: center;margin-top: 1.08333vh'>" + displyTime + "</div>" +
                    "</div>" +
                    "<div class='approval_style_comment' comment_id='"+ id +"'></div>";

        var html_img = "";

        var html_file = "";

        var html_end = "</div></div></div>";

        if(comment_img!=""){
            for(var i=0;i<img_arr.length;i++){
                html_img += "<img class='detail_approval_date_pic' src='"+img_arr[i]+"'>"
            }
        }
        if(comment_file!=""){
            for(var j=0;j<files.length;j++){
                var file_name = files[j].file_name;
                var file_size = files[j].file_size;
                var file_url  = files[j].file_url;

                var isImg = checkImageType(file_name);
                var file_icon = "../approvalImg/Giab/file_icon.png";
                if (isImg == false){
                    file_icon = "../approvalImg/word.png";
                }

                html_file +="<div class='comment_big file_download' file_data='"+file_url+"' file_name='"+file_name+"'>" +
                    "<div class='col-xs-3' style='height: 100%'>" +
                    "<img src='"+ file_icon +"' class='comment_img'></div>" +
                    "<div class='col-xs-9'>" +
                    "<div class='file_name'>"+file_name+"</div>" +
                    "<div class='file_size'>"+file_size+"</div></div></div>";
            }
        }

        var img_content_html = "<div class='comment_img_cotent'>";
        var html = html_start+img_content_html+html_img+html_file+html_end;

        if (isLast == true && cancel_status != "2"){
            //最后一条
            var html3 = "";
            if (status == "0" && cancel_status == "-1"){
                html3 = "<div class='detail_tableview_cell_div'>"+html+"</div>";
            }else {
                html3 = "<div class='detail_tableview_cell_div2'><div class='finishDiv'></div>"+html+"</div>";
            }

            $(".comment_div").append(html3);
        }else {
            var html2 = "<div class='detail_tableview_cell_div'>"+html+"</div>";
            $(".comment_div").append(html2);
        }

        var i = setInterval(function() {
            var obj = $(".approval_style_comment[comment_id='"+ id +"']");

            if (obj.length > 0){
                obj.html(comment_body);
                clearInterval(i);
            }
        }, 1000);
    }


    function displayApproveDetail(detail,userInfo,isLast,status,is_last_relation,cancel_status){
        var img_url         = "";
        var result          = "";
        var result_grey     = "";
        var add_html        = "";

        var userId         = detail.user_id;
        var approval_name;
        var approval_icon;
        var approval_qyxBindId;

        for(key in userInfo){
            if(userInfo[key].id==userId){
                approval_name       = userInfo[key].name;
                approval_icon       = userInfo[key].avatar;
                approval_qyxBindId  = userInfo[key].qyxBindId;
            }
        }
        var img_url1;
        //if(approval_icon==""){
            var color1 = avatar_getColor(approval_qyxBindId);
            img_url1 = "<div class='detail_left_pic2' style='background-color: "+color1+"'>"+avatar_name(approval_name)+"</div>"
        //}else{
        if (approval_icon.length > 0) {
            var src1 = avatar_getUrl(_userId,_token,approval_icon);
            img_url1 += "<img class='detail_left_pic2' src='"+src1+"' hidden>";
        }
        var approval_result = detail.approval_result;
        var approval_img    = detail.approval_img;
        var approval_file   = detail.approval_file;
        var details_files   = detail.files;
        var timestamp       = detail.timestamp;
        var img_arr         = approval_img.split(",");

        //console.log(timestamp);

        if(approval_result==0){
            img_url = "../approvalImg/disagree.png";
            result = "审批拒绝";
            if (detail.reason.length > 0){
                result_grey = "("+ detail.reason +")";
            }else {
                result_grey = "(拒绝)";
            }
            add_html = "<div  class='approval_style_disagree'>"+result+"<span class='agree'>"+result_grey+"</span></div>";
        }else if(approval_result==1){
            img_url = "../approvalImg/green_right.png";
            result = "审批通过";

            if (detail.reason.length > 0){
                result_grey = "("+ detail.reason +")";
            }else {
                result_grey = "(同意)";
            }
            add_html = "<div  class='approval_style2'>"+result+"<span class='agree'>"+result_grey+"</span></div>";
        }

        if(index==0){
            if(approval_result==0||approval_result==1){
                if(localStorage.user_id==userId){
                    index=1;
                }
            }
        }
        var html_img_do="";
        if(approval_img!=""){
            for(var z=0;z<img_arr.length;z++){
                html_img_do += "<img class='detail_approval_date_pic' src='"+img_arr[z]+"'>"
            }
        }else{
            html_img_do=""
        }
        var html_file_do="";
        if(approval_file!=""){
            for(var j=0;j<details_files.length;j++){
                var file_name_do = details_files[j].file_name;
                var file_size_do = details_files[j].file_size;
                var file_url_do  = details_files[j].file_url;

                var isImg = checkImageType(file_name_do);
                var file_icon = "../approvalImg/Giab/file_icon.png";
                if (isImg == false){
                    file_icon = "../approvalImg/word.png";
                }

                html_file_do +=
                    "<div class='comment_big file_download' file_data='"+file_url_do+"' file_name='"+file_name_do+"' style='margin-left: 14vw;margin-bottom: 1vh'>" +
                        "<div class='col-xs-3' style='height: 100%'>" +
                            "<img src='"+ file_icon +"' class='comment_img'>" +
                        "</div>" +
                        "<div class='col-xs-9'>" +
                            "<p class='file_name'>"+file_name_do+"</p>" +
                            "<p class='file_size'>"+file_size_do+"</p>" +
                        "</div>" +
                    "</div>";
            }
        }else{
            html_file_do="";
        }


        var displayTime = timestampToString(Math.round(timestamp),"yyyy.MM.dd HH:mm");

        var html1 =
            "<div class='approval_name_comment'>" +
                "<div class='col-xs-6 approval_name_do' style='padding-left: 0px;'>"+approval_name+"</div>" +
                "<div class='col-xs-6 detail_time' style='text-align: center;margin-top: 1.08333vh'>"+ displayTime +"</div>" +
            "</div>";
        //var html2 = "<div class='approval_name2'>"+approval_name+"</div>";
        var html_process =
            "<div class='do_bigest'>"+
                "<div class='detail_tableview_cell_mid_do'>" +
                    "<img src='" + img_url + "' class='green_right'>"+
                    "<div class='detail_left_small2 col-xs-2' style='height: 100%'>" + img_url1 + "</div>" +
                    "<div class='detail_right_small2 col-xs-10'>" +
                        html1 + add_html + "</div>" +
                    "</div>" +
                "<div class='do_img_content'>" + html_img_do + "</div>" +
                html_file_do +
            "</div>";



        if (isLast == true){
            //最后一条


            if (status == "0"){
                //最后一条 有下个
                var html2 = "<div class='detail_tableview_cell_div'>"+html_process+"</div>";
                $(".comment_div").append(html2);
                //if (is_last_relation == true ){
                //    if (cancel_status == "2"){
                //        $(".comment_div").append(current_html2);
                //    }else {
                //        $(".comment_div").append(current_html3);
                //    }
                //
                //}
            }else {
                //最后一条 没有下一个
                if (cancel_status == "2"){
                    //后面有撤销
                    var html3 = "<div class='detail_tableview_cell_div'>"+html_process+"</div>";
                    $(".comment_div").append(html3);
                }else {
                    var html3 = "<div class='detail_tableview_cell_div2'><div class='finishDiv'></div>"+html_process+"</div>";
                    $(".comment_div").append(html3);
                }
            }

        }else {
            var html2 = "<div class='detail_tableview_cell_div'>"+html_process+"</div>";
            $(".comment_div").append(html2);
            //if (status == "0" && is_last_relation == true){
            //    //有下一条
            //    $(".comment_div").append(current_html2);
            //}
        }
    }


    //页面进入后的数据加载
    initData();

    //点击查看大图
    $(document).on('click', '.detail_approval_date_pic', function () {
        $.watchBigPic($(this));
    });

    //点击下载文件
    var downloadFile;
    downloadFile = document.createElement('iframe');
    downloadFile.style.display = 'none';
    document.documentElement.appendChild(downloadFile);
    $(document).on('click','.file_download',function(){
        var file_data = $(this).attr("file_data");
        var file_name = $(this).attr("file_name");

        downloadFile.src = "/downloadFile_downThisFile?url=http://"+file_data+"&fileName="+file_name+"";
    });

    //点击 同意  拒绝  评论
    $(".agree_btn").on('click',function(){
        three_btn="agree";
        $(".show_detail").hide();
        $(".show_ARC").show();
        operateType = "1";
        $("#rel_input_box").attr("placeholder","请输入同意理由(非必填)");
        $("#title").val("审批意见");
    });
    $(".refuse_btn").on('click',function(){
        three_btn="refuse";
        $(".show_detail").hide();
        $(".show_ARC").show();
        operateType = "0";
        $("#rel_input_box").attr("placeholder","请输入拒绝理由(非必填)");
        $("#title").val("审批意见");
    });
    $(".comment_btn").on('click',function(){
        three_btn="comment";
        $(".show_detail").hide();
        $(".show_ARC").show();
        $("#rel_input_box").attr("placeholder","说点什么吧");
        $("#title").html("评论");
    });


    /*
    * 跳转到
    * 同意拒绝评论界面的js
    *
    * */
    var operateType;            //同意  拒绝
    //联系人全局
    var contact_arr         = [];
    var contact_name_arr    = [];

    var temp_arr            = [];
    var temp_name_arr       = [];
    $("#approval_do_back").on('click',function(){
        $("#rel_input_box").html("");
        $(".img_based").remove();
        $(".file_content").remove();
        $(".show_detail").show();
        $(".show_ARC").hide();
    });

    //点击图片进行选择
    $("#camera").on('click',function(){
        $("#upload").click();
    });
    $("#upload").change(function(d){
        var formdata=new FormData($("#form")[0]);

        formdata.append("type","0");
        formdata.append("names", "img");

        var file = this.files[0];
        if (file != undefined){
            var file_name = file.name;
            var file_type = file.type;
            var type = file_type.split("/")[0];

            //var type = file_name.split(".")[1];
            //if(type=="jpg"||type=="png"||type=="jpeg"){
            if(checkImageType(file_name)==true) {
            //if(type=="image"){
                var lastImg;
                $.ajax({
                    beforeSend:function(){
                        var img_html = "<div class='img_based'>" +
                            "<img src='../approvalImg/loading.gif' class='img'>" +
                            "<img src='../approvalImg/delete.png' class='img_delete'>" +
                            "</div>";
                        $(".pic_content").append(img_html);
                        lastImg = $(".img_based .img").last();
                    },
                    type : 'POST',
                    url : apiurl+'/global/upload',
                    data: formdata,
                    cache : false,
                    processData : false,
                    contentType : false,
                    mimeType:"multipart/form-data",
                    success : function(d){
                        var data_url=JSON.parse(d).data;
                        lastImg.attr("src","http://"+data_url+"");
                        if($(".img").length>8){
                            $(".call_back_success").html("最多上传9张图片").show().fadeOut(2000);
                            $("#camera").hide();
                        }
                    }
                });
            }else {
                $(".call_back_success").html("不支持该图片类型!").fadeIn();
                setTimeout(function(){
                    $(".call_back_success").fadeOut(1000);
                },1000);
            }
        }
        //清空重置控件
        var imgInput = $('#upload');
        imgInput.replaceWith(imgInput.val('').clone(true));
    });
    //点击上传文件
    $("#file_add").on('click',function(){
        var fileInput = $('#upload_file');
        fileInput.replaceWith(fileInput.val('').clone(true));
        $("#upload_file").click();
    });

    $("#upload_file").change(function(){

        var formdata = new FormData($("#form_file")[0]);
        var file = this.files[0];
        if(file!=undefined){
            var file_size_k = file.size;
            var file_size;
            if(file_size_k<1000){
                file_size = Math.round(file_size_k) + "B";
            }else if(file_size_k<1000000){
                file_size = Math.round(file_size_k/1024) + "KB";
            }else{
                file_size = Math.round(file_size_k/1024/1024) + "MB";
            }
            var file_name = file.name;
            var file_type = file.type;
            var type = file_type.split("/")[0];

            if (checkFileType(file_name) == true){
                formdata.append("type","1");
                formdata.append("file_size", file_size);
                $.ajax({
                    beforeSend:function(){
                        var html="<img src='../approvalImg/loading.gif' class='loading_file'>";
                        $(".file_content").last().append(html);
                    },
                    type : 'POST',
                    url : apiurl+'/global/singleUpload',
                    data: formdata,
                    cache : false,
                    processData : false,
                    contentType : false,
                    mimeType:"multipart/form-data",
                    success : function(d){

                        var file_icon = "../../approval/approvalImg/word.png";
                        if (type == "image"){
                            file_icon = "../../approval/approvalImg/Giab/file_icon.png";
                        }
                        $(".loading_file").hide();
                        var data_url=JSON.parse(d).data;
                        var file_id = data_url.file_id;
                        var file_html = "" +
                            "<div class='file_content'>" +
                                //"<div class='col-xs-1 content_height'>" +
                                //"<div class='col-xs-10 content_height'>" +
                            "<img src='"+ file_icon +"' class='file_img'>" +
                                //"</div>" +
                                //"</div>" +
                            "<div class='col-xs-9 content_height'>" +
                            "<div class='file_name_insert' data-id='"+file_id+"'>"+file_name+"</div>" +
                            "<div class='file_size'>"+file_size+"</div>" +
                            "</div>" +
                            "<div class='col-xs-1 delete_img_red'>" +
                            "<img class='enclosure_delete' src='../approvalImg/delete.png'>" +
                            "</div>" +
                            "</div>";

                        $(".file_div").append(file_html);
                        if($($(".file_div").find(".file_content")).length > 8){
                            $(".call_back_success").html("最多上传9个附件").show().fadeOut(2000);
                            $("#file_add").hide();
                        }
                    }
                });
            }else {
                $(".call_back_success").html("不支持该文件类型!").fadeIn();
                setTimeout(function(){
                    $(".call_back_success").fadeOut(1000);
                },1000);
            }
        }
        //清空重置控件
        var fileInput = $('#upload_file');
        fileInput.replaceWith(fileInput.val('').clone(true));
    });

    //$("#upload_file").blur(function(){
    //    console.log("blur");
    //    var fileInput = $('#upload_file');
    //    fileInput.replaceWith(fileInput.val('').clone(true));
    //});

    //删除图片
    $(document).on('click','.img_delete',function(){
        $(this).parent().remove();
        $("#camera").show();
    });

    //删除文件
    $(document).on('click','.enclosure_delete',function(){
        $(this).parent().parent().remove();
        $("#file_add").show();
    });

    //上传意见(同意拒绝)
    $(".approval_do_nav_right").on('click',function(){
        //textarea的值
        var val = $("#rel_input_box").html();


        //图片
        var img_arr = [];
        var img_str;
        $(".img").each(function(index){
            img_arr[index]=$(this).attr("src");
        });
        img_str = img_arr.join(",");
        //文件
        var file_arr = [];
        var file_str;
        $(".file_name_insert").each(function(index){
            file_arr[index]=$(this).attr("data-id");
        });
        file_str = file_arr.join(",");
        //获取followers;
        var followers_id_arr   = [];
        var followers_name_arr = [];
        var temp_followers_arr = [];
        var followers_id       = "";
        //---先去重
        for(var a in temp_arr){
            if(followers_id_arr.indexOf(temp_arr[a])==-1){
                followers_id_arr.push(temp_arr[a]);
            }
        }
        for(var b in temp_name_arr){
            if(followers_name_arr.indexOf(temp_name_arr[b])==-1){
                followers_name_arr.push(temp_name_arr[b]);
            }
        }
        //---再对照文本类型里的文字  看看有无该人;
        for(var x=0;x<followers_name_arr.length;x++){
            if(val.indexOf(followers_name_arr[x])==-1){
                temp_followers_arr.push(followers_name_arr[x]);
            }
        }
        for(var k in temp_followers_arr){
            for(var v in followers_name_arr){
                if(temp_followers_arr[k]==followers_name_arr[v]){
                    followers_name_arr.splice(v,1);
                    followers_id_arr.splice(v,1);
                }
            }
        }
        if(followers_id_arr.length>0){
            followers_id = followers_id_arr.join(",");
        }

        //数据的获取 展示
        var data;
        var url;
        var type;
        if(three_btn=="comment"){
            data={
                user_id:_userId,
                comment_body:val,
                comment_img:img_str,
                comment_file:file_str,
                followers:followers_id,
                token:_token,
                imtoken:_imToken,
                qyxBindId:_qyxBindId,
                title:_name+"的"+_title+"有新的评论"
            };
            url = apiurl+"/approvals/"+approval_id+"/comment";
            type = "POST";
            if(val=="") {
                $(".call_back_success").html("评论内容不能为空").show().fadeOut(2000);
                return;
            }
        }else{
            data={
                user_id:_userId,
                operateType:operateType,
                reason:val,
                approval_img:img_str,
                approval_file:file_str,
                followers:followers_id,
                token:_token,
                imtoken:_imToken,
                qyxBindId:_qyxBindId,
                title:_name+"的"+_title+"状态更新"
            };
            url = apiurl+"/approvals/"+approval_id+"/operate";
            type = "PUT";
        }
        $.ajax({
            beforeSend:function(){
                $(".call_back_success").html("正在提交...").show()
            },
            url:url,
            type:type,
            data:data,
            success:function(d){
                var msg= d.msg;
                var data = JSON.parse(d);
                if(msg=="202") {
                    $(".token_iframe").fadeIn(1000);
                }
                if(data.code=="0"){
                    $(".call_back_success").hide();
                    $(".call_back_success").html("提交成功").show().fadeOut(1000,function(){
                        window.location.reload();
                    });
                }else{
                    $(".call_back_success").html(data.msg);
                }
            }
        })
    });


    $(document).on('click','#remindMe',function(){
        $(".model_div").hide();
        $(".contact_div").show();
        //获取输入框的文字  判断 是否
        var val = $("#rel_input_box").html();

        contact_name_arr = [];
        contact_arr      = [];
        initpart();
    });

    //点击返回
    $(".contact_back").on('click',function(){
        $(".contact_div").hide();
        $(".model_div").show();
        $(".team_bigest").remove();
        $(".user_mid").remove();
        $(".group_name_div").remove();
        contact_arr      = [];
        contact_name_arr = [];
    });
    //加载部门列表 以及默认的成员
    function getTeamName(){
        var url_c  = tk_apiurl+"contacteam/findone";
        var data = {"userId":_userId,"token":_token,"data":JSON.stringify({'id':localStorage.group_id})};

        $.ajax({
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d) {
                var data1 = '';
                var status = '';

                data = eval('(' + d + ')');
                status = data.statusCode;
                if (data.result) {
                    data1 = eval('(' + data.result + ')');
                }
                teamName = data1.teamName;


            }
        });
    }


    function approvalDepartment(){
        var url_c  = tk_apiurl+"contacteam/findone";
        var data = {"userId":_userId,"token":_token,"data":JSON.stringify({'id':localStorage.group_id})};

        $.ajax({
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d) {
                var data1 = '';
                var status = '';

                data = eval('(' + d + ')');
                status = data.statusCode;
                if (data.result) {
                    data1 = eval('(' + data.result + ')');
                }

                $("#depart").html(data1.teamName);

                //teamName = ;


            }
        });
    }


    function initpart(){
        var url_c  = tk_apiurl+"contacteam/mydepts";
        var data = {"userId":_userId,"token":_token,"data":JSON.stringify({'teamId':_group_id,'parentId':"0"})};
        $.ajax({
            beforeSend:function(){
                $(".loading_c").show();
                $(".contact_bigest").hide();
            },
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){
                var data='';
                var data1='';
                var status='';

                data = eval('('+d+')');
                status = data.statusCode;
                if(data.result){
                    data1 = eval('(' + data.result + ')');
                }
                if(status==202){
                    $(".token_iframe").fadeIn(1000);
                }
                else {
                    $(".loading_c").hide();
                    //title
                    $(".contact_title").html(teamName);
                    //contact_bigest添加名称条
                    var contact_name_html = "<div class='group_name_div'>"+teamName+"<img src='../approvalImg/contact.png' class='group_img'></div>";
                    $(".contact_bigest").show().prepend(contact_name_html);
                    //加载部门列表
                    var team = data1.depts;

                    for(var i=0;i<team.length;i++){
                        var html="<div class='team_bigest' id='"+team[i].id+"'>" +
                            "<div class='team_mid' is_choice='0'>" +
                            "<div class='team_left'>" +
                            //"<img src='../../approval/approvalImg/team.png' class='team_pic'>" +
                            "<div class='team_name'>"+team[i].departmentName+"</div>" +
                            "</div>" +
                            "<div class='team_right'>" +
                            "<img src='../../log/logImg/rightIcon.png' class='right_icon'></div></div>" +
                            "</div>";
                        $(".team_content_bigest").append(html);
                    }


                    //加载成员列表
                    var users = data1.users;

                    var html_user="";

                    for(var a=0;a<users.length;a++){
                        var _choice = "0";
                        //var _img    = "<img src='../../log/logImg/tick.png' class='tick_icon'>";
                        var _img = "<img src='../../task/images/task/circleCheckBoxUnselect.png' class='round_tick'>";
                        for(var j=0;j<contact_arr.length;j++){
                            if(contact_arr[j]==users[a].userId){
                                _choice = "1";
                                _img    = "<img src='../../task/images/task/circleCheckBoxSelect.png' class='round_tick'>";
                            }
                        }


                        var img_url;
                        var avatar1 = users[a].avatar;
                        var qyxBindId = users[a].userIM;
                        var name = users[a].userName;

                        //if(avatar1==""){
                            var color = avatar_getColor(qyxBindId);
                            img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                        //}else{
                        if (avatar1.length > 0) {
                            var src = avatar_getUrl(_userId,_token,avatar1);
                            img_url += "<img src='"+src+"' class='user_pic' hidden>";
                        }


                        //html_user +="<div class='user_mid' id='"+users[a].userId+"' name='"+users[a].userName+"' is_choice='"+_choice+"'>" +
                        //    "<div class='user_left'>" +
                        //    ""+img_url+"" +
                        //    "<div class='user_name'>"+users[a].userName+"</div>" +
                        //    "</div>" +
                        //    "<div class='user_right'>" +
                        //    ""+_img+"</div></div>";

                        html_user +="<div class='user_mid' id='"+users[a].userId+"' qyxBindId='"+qyxBindId+"' name='"+users[a].userName+"' avatar='"+users[a].avatar+"' is_choice='"+_choice+"'>" +
                            "<div class='choice_it_div'>"+_img+"</div>" +
                            "<div class='user_left'>" +
                            ""+img_url+"" +
                            "<div class='user_name'>"+users[a].userName+"</div>" +
                            "</div>" +
                            "</div>";

                    }
                    $(".contact_content").append(html_user);

                    //最后一个部门的border-bottom隐藏
                    $(".team_mid").each(function(){
                        $(this).last().css('borderBottom','0');
                    });

                    showAvatar(".user_pic");

                }
            }
        });
    }
    //点击行获取部门下的成员列表
    var _team;
    $(document).on('click','.team_mid',function(){
        $(this).css("borderBottom","1px solid #e5e5e5");
        _team = $(this).parent();
        var is_choice = $(this).attr("is_choice");
        if(is_choice=="0"){
            $(".right_icon").addClass('right_icon_down').attr('src','../../task/images/task/arrow.png');
            var deptId = $(_team).attr("id");
            var url    = tk_apiurl+"contacteam/mydeptsall";
            var data   = {"userId":_userId,"token":_token,"data":JSON.stringify({'teamId':group_id,'deptId':deptId})};
            $.ajax({
                async: true,
                crossDomain: true,
                url: url,
                method: "POST",
                data:data,
                jsonpCallback:"jsoncallback",
                dataType: "jsonp",
                success:function(d){
                    var data='';
                    var data1='';
                    var status='';

                    data = eval('('+d+')');
                    status = data.statusCode;
                    if(data.result){
                        data1 = eval('(' + data.result + ')');
                    }
                    if(status==202){
                        $(".token_iframe").fadeIn(1000);
                    }
                    else {
                        var users = data1.users;

                        var html="";

                        for(var i=0;i<users.length;i++){
                            var _choice = "0";
                            //var _img    = "<img src='../../log/logImg/tick.png' class='tick_icon'>";
                            var _img    = "<img src='../../task/images/task/circleCheckBoxUnselect.png' class='round_tick'>";
                            for(var j=0;j<contact_arr.length;j++){
                                if(contact_arr[j]==users[i].userId){
                                    _choice = "1";
                                    _img    = "<img src='../../task/images/task/circleCheckBoxSelect.png' class='round_tick'>";
                                }
                            }


                            var img_url;
                            var avatar1 = users[i].avatar;
                            var qyxBindId = users[i].userIM;
                            var name = users[i].userName;
                            //if(avatar1==""){
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                            //}else{
                            if (avatar1.length > 0){
                                var src = avatar_getUrl(_userId,_token,avatar1);
                                img_url += "<img src='"+src+"' class='user_pic' hidden>";
                            }

                            //html +="<div class='user_mid' id='"+users[i].userId+"' name='"+users[i].userName+"' is_choice='"+_choice+"'>" +
                            //    "<div class='user_left'>" +
                            //    ""+img_url+"" +
                            //    "<div class='user_name'>"+users[i].userName+"</div>" +
                            //    "</div>" +
                            //    "<div class='user_right'>" +
                            //    ""+_img+"</div></div>";
                            html +="<div class='user_mid' id='"+users[i].userId+"' qyxBindId='"+qyxBindId+"' name='"+name+"' avatar='"+avatar1+"' is_choice='"+_choice+"'>" +
                                "<div class='choice_it_div'>"+_img+"</div>" +
                                "<div class='user_left'>" +
                                ""+img_url+"" +
                                "<div class='user_name'>"+users[i].userName+"</div>" +
                                "</div>" +
                                "</div>";

                        }
                        $(_team).append(html);

                        $(".user_mid").last().css("border","none");

                        showAvatar(".user_pic");
                    }
                }
            });
            $(this).attr("is_choice","1");
        }else{
            $(".right_icon").removeClass('right_icon_down').attr('src','../../log/logImg/rightIcon.png');
            $(this).nextAll().hide();
            $(this).attr("is_choice","0");
        }
    });

    //选择联系人
    $(document).on('click','.user_mid',function(){
        var id        = $(this).attr('id');
        var name      = $(this).attr('name');
        var is_choice = $(this).attr("is_choice");

        if(is_choice=="0"){
            //$($(this).children(1)[1]).children(0).show();
            $($(this).find('.round_tick')).attr('src','../../task/images/task/circleCheckBoxSelect.png');
            $(this).attr("is_choice","1");
            contact_arr.push(id);
            contact_name_arr.push("@"+name);

            temp_arr.push(id);
            temp_name_arr.push("@"+name);

        }else{
            //$($(this).children(1)[1]).children(0).hide();
            $(this).find('.round_tick').attr('src','../../task/images/task/circleCheckBoxUnselect.png');
            $(this).attr("is_choice","0");
            for(key in contact_arr){
                if(contact_arr[key]==id){
                    contact_arr.splice(key,1);
                }
            }
            for(na in contact_name_arr){
                if(contact_name_arr[na]=="@"+name){
                    contact_name_arr.splice(key,1);
                }
            }
        }
    });

    //点击确定
    $(".contact_choice").on('click',function(){
        $(".contact_div").hide();
        $(".model_div").show();
        $(".team_bigest").remove();
        $(".copy_me_person").remove();
        $(".user_mid").remove();
        $(".group_name_div").remove();
        for(var i=0,j= 0;i<contact_arr.length,j<contact_name_arr.length;i++,j++){
            var div = "<div contenteditable='true' style='width: auto;max-width: 100%; height: auto; display: inline-block;'><span contentEditable='false' style='color: #18CC9C;margin-left: 0.5vw;margin-right: 0.5vw'>"+contact_name_arr[j]+"</span></div>";
            $("#rel_input_box").append(div);
        }

        temp_arr      = contact_arr;
        temp_name_arr = contact_name_arr;

    });



    //个人信息
    function getPersonInfo(userId){
        var url_c  = tk_apiurl+"user/userinfo";
        var data = {"userId":userId,"token":_token,"data":JSON.stringify({'userId':userId})};
        $.ajax({
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){

                var data='';
                var data1='';
                var status='';

                data = eval('('+d+')');
                status = data.statusCode;
                if(data.result){
                    data1 = eval('(' + data.result + ')');
                }
                if(status==202){
                    $(".token_iframe").fadeIn(1000);
                }
                else {
                    teamName = data1.teamName;
                }
            }
        });
    }

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }
});